from socket import *
from threading import Thread
import re

FILE = '.'

def response(clientSock):
    #响应http请求

    data = clientSock.recv(1024)
    new_data = data.decode().splitlines()[0]
    new_data = re.match(r"\w+ +(/[^ ]*) ", new_data).group(1)
    print(new_data)

    http_response = 'HTTP/1.1 200 OK\r\n'
    http_headers = "Server: my server\r\n"
    
    if new_data == '/':
        new_data = '/index.html'
    try:
        f = open(FILE+new_data, 'r')
        http_body = f.read()
    except:
        http_response = 'HTTP/1.1 404 not fond\r\n'
        http_headers = "Server: my server\r\n"
        http_body = 'not find'
    else:
        f.close()

    httpData = http_response + http_headers +"\r\n"+ http_body
    clientSock.send(bytes(httpData, 'utf-8'))

def main():

    sock = socket(AF_INET, SOCK_STREAM)
    sock.bind(("", 8888))
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sock.listen(128)

    while True:

        #为每一个客户端常见一个线程
        clientSock, addr = sock.accept()
        tr = Thread(target=response, args=(clientSock,))

        print(addr)
        tr.start()

    clientSock.close()


if __name__ == "__main__":
    main()
